package com.aring.deals.actions;

import java.io.PrintWriter;
import java.lang.reflect.Type;

import org.apache.struts2.ServletActionContext;

import com.aring.constant.ResultCode;
import com.aring.deals.bean.JsonBean;
import com.aring.deals.bean.User;
import com.aring.deals.listener.OptionListener;
import com.aring.deals.option.UserOption;
import com.aring.deals.tool.Common;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class RegisterAction extends ActionSupport{
    
	private PrintWriter out;
    private String firstName;
	private String lastName;
	private String account;
	private String password;
	
	
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		   if(password==null) this.password = password;
		   else this.password = Common.getMD5Str(password);
	}
	

	public String execute() throws Exception {
		
		User user = new User();
		user.setAccount(account);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setPassword(password);
	    out = ServletActionContext.getResponse().getWriter(); 
	    UserOption.register(user, new OptionListener<User>() {
			
			@Override
			public void onSuccess(User user) {
				JsonBean<User> jsonUser = new JsonBean<User>();
				user.setProductOrders(null);
				user.setWithdrawOrders(null);
				user.setPassword(null);
				user.setWithdrawPassword(null);
				jsonUser.setResultCode(ResultCode.SUCCESS_CODE);
				jsonUser.setResult(user);
			    Type type = new TypeToken<JsonBean<User>>() {}.getType();
				out.write(Common.<JsonBean<User>>packageJson(jsonUser,type));      
				out.flush();
				out.close();
			}

			@Override
			public void onFailure(int resultCode) {
				JsonBean<String> json = new JsonBean<String>();
				json.setResultCode(resultCode);
			    Type type = new TypeToken<JsonBean<String>>() {}.getType();
				out.write(Common.<JsonBean<String>>packageJson(json,type));  
				out.flush();
				out.close();
			}
		});
        return null;
	}
}
